<?php
class Admin_AuthController extends Zend_Controller_Action {
	
	public function init() {
		$layoutPath = TEMPLATE_PATH  . '/admin';
		$option = array ('layout' => 'login',
                   'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );
		
		// Css
		$file_uri = $this->view->baseUrl(ADMIN_PATH . '/css/style_login.css');
		$this->view->headLink()->setStylesheet($file_uri);
	}
	
	public function indexAction() {
		// Title
		$this->view->headTitle('Đăng nhập');
		if(Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/admin/index');
        }
        
		if ($this->_request->isPost()) {

			//1.Goi ket noi voi Zend Db
			$db = Zend_Registry::get('connectDB');
			//$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
			//2. Khoi tao Zend Autho
			$auth = Zend_Auth::getInstance ();

			//3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
			$authAdapter = new Zend_Auth_Adapter_DbTable($db);
			$authAdapter->setTableName('tb_users_admin')
						->setIdentityColumn('email')
						->setCredentialColumn('password');
			
			//4. Lay gia tri duoc gui qua tu FORM
			$uname = $this->_request->getParam('username');
			$paswd = Zendhlt_Encode::password($this->_request->getParam('password'));
			
			//5. Dua vao so sanh voi du lieu khai bao o muc 3
			$authAdapter->setIdentity($uname);
			$authAdapter->setCredential($paswd);

			//6. Kiem tra trang thai cua user neu IDGROUP > 2 moi duoc login
			$select = $authAdapter->getDbSelect();

			//7. Lay ket qua truy van
			$result = $auth->authenticate($authAdapter);
			$flag = false;
			if ($result->isValid()) {
				//8. Lay nhung du lieu can thiet trong bang users neu login thanh cong
				$data = $authAdapter->getResultRowObject(array('id', 'ho_ten', 'email', 'role'), array('password'));
				$role = new Admin_Model_RoleMapper();
				$value = $role->fetchAll('id='.$data->role);
				$data->rolename = $value[0]->getTen_quyen_han();
				
				//9. Luu nhung du lieu cua member vao session
				$auth->getStorage()->write($data);
				$flag = true;
			}
			
			if ($flag == true) {
				$infoUser = $auth->getIdentity();
				$this->_redirect('/admin/index');
			} else {
				$this->view->note = '*Tài khoản không tồn tại.';
			}
		}
	}
	
	public function logoutAction() {
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->_redirect('/admin/auth');
	}
}